package com.travel.Config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@Component
public class SecuritySuccessHandler  implements AuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;



    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String role = null;
        //项目根地址
        String path = request.getContextPath();
        //主机+端口号+项目根路径
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

        UserDetails principal =(UserDetails) authentication.getPrincipal();
        //权限是我手动赋予的，每一个认证成功的用户只有一个权限
        Collection<? extends GrantedAuthority> authorities = principal.getAuthorities();
        for (GrantedAuthority  authority:authorities) {
            //所以authorities的size为1，直接赋予
            role = authority.getAuthority();
        }
        //通过不同的角色转到不同的页面
        if(Objects.equals(role, "ROLE_user")) {
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("code",200);
            map.put("message","登录成功");
            map.put("data",authentication);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(objectMapper.writeValueAsString(map));
            out.flush();
            out.close();
//            response.sendRedirect(basePath+"admin/login.html");
        }else if(Objects.equals(role, "ROLE_super") || Objects.equals(role, "ROLE_admin")){
            response.sendRedirect("/SuperPage/sIndex");
        }
    /*    else {
            System.out.println("其他");
            response.sendRedirect(basePath+"login.html");
        }*/
    }
}
